/**
 * 
 */

package com.tdam2014.grupo3.tasks;

import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.widget.ImageView;

import com.tdam2014.grupo3.flickr.util.images.ImageUtils;
import com.tdam2014.grupo3.utils.ImagesUtils;

/**
 * Represents the image download task which takes an image URL as the parameter,
 * after the download, set the bitmap to an associated ImageView.
 * 
 * @author Lucas Cunibertti
 */
public class ImageDownloadTask extends AsyncTask<String, Integer, Bitmap> {
	
	private ImageView imageView;
	private String mUrl;
	private boolean isProfileImage;
	private String peopleNSID;
	private String photoSetID;
	private String photoID;

	/**
	 * Constructor for download profile images
	 * 
	 * @param imageView
	 * @param isProfileImage
	 * @param peopleNSID
	 */
	public ImageDownloadTask(ImageView imageView, boolean isProfileImage,
			String peopleNSID) {
		this.imageView = imageView;
		this.isProfileImage = isProfileImage;
		this.peopleNSID = peopleNSID;
	}

	/**
	 * Constructor for download thumbs images
	 * 
	 * @param imageView
	 * @param isProfileImage
	 * @param photoSetID
	 * @param photoID
	 */
	public ImageDownloadTask(ImageView imageView, boolean isProfileImage,
			String photoSetID, String photoID) {
		this.imageView = imageView;
		this.isProfileImage = isProfileImage;
		this.photoSetID = photoSetID;
		this.photoID = photoID;
	}

	@Override
	protected Bitmap doInBackground(String... params) {
		mUrl = params[0];
		return ImageUtils.downloadImage(mUrl);
	}

	@Override
	protected void onPostExecute(Bitmap result) {
		if (this.isCancelled()) {
			result = null;
			return;
		}
		
		if(result != null) {
			String path;
			if (isProfileImage) path = ImagesUtils.PROFILES_PATH + peopleNSID + ".jpg";
			else path = ImagesUtils.THUMBS_PATH + photoSetID + "_" + photoID + ".jpg";
			
			ImagesUtils.saveImage(result, path);
			imageView.setImageBitmap(result);
		}
	}
}
